#!/home/kamal/work/iamalive/pythonenv/bin/python
# $Id: xtalk.py,v 1.2 2006/10/06 12:30:42 normanr Exp $
import sys,os,xmpp,time,select,logging,threading

sys.path.append('.')
from daemon import Daemon
import sysv_ipc

LOG_FILENAME='/home/kamal/work/iamalive/bot/python_xmpp_bot/imapresencesubscriber.log'
APP_NAME='ImaPresenceSubscriberDaemon'
CONF_FILENAME='/home/kamal/work/iamalive/bot/python_xmpp_bot/ima_xmpp_bot.conf'
PID_FILENAME='/home/kamal/work/iamalive/bot/python_xmpp_bot/ima_presence_subscriber.pid'

# create logger
logger=logging.getLogger(APP_NAME)
logger.setLevel(logging.INFO)

#add a file handler
lfh=logging.FileHandler(LOG_FILENAME)
#lfh=logging.TimedRotatingFileHandler(LOG_FILENAME, 'midnight', 1, backupCount=5)
lfh.setLevel(logging.INFO)
#log.rotator=GZipRotator()

# create a formatter and set the formatter for the handler.
#logFormatter= logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logFormatter=logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - FILE: %(filename)s - LINE: %(lineno)d - %(message)s')
lfh.setFormatter(logFormatter)

# add the Handler to the logger
logger.addHandler(lfh)

class ImaPresenceSubscriber(Daemon):
	def __init__(self):
		logger.info('ImaPresenceSubscriber.__init__ called')
		#self.jid=xmpp.protocol.JID('kamal@iamalive.in')
		self.client=None
		self.con=None
		self.auth=None
		#self.socketlist={}
		self.mq=None
		#self.roster=None
		Daemon.__init__(self, PID_FILENAME)

	def read_conf_file(self):
		logger.warn('ImaPresenceSubscriber.read_conf_file called')
		self.params={}
		logger.info('conf file is :' + CONF_FILENAME)
		if os.access(CONF_FILENAME, os.R_OK):
			logger.info('conf file is accessible')
			for ln in open(CONF_FILENAME).readlines():
				logger.info('line is : ' + ln)
				if not ln[0] in ('#',';'):
					logger.info('parsing line')
					ln=ln.strip()
					if ( ln.__len__() > 3 ):
						key,val=ln.split('=',1)
						self.params[key.lower()]=val

			logger.info('read and parsed the conf file')

			for mandatory in ['jid','password','subscriber_resource','tracker_resource','mq_id']:
				if mandatory not in self.params.keys():
					open(CONF_FILENAME).write('#Uncomment fields before use and type in correct credentials.\n#JID=romeo@montague.net/resource (/resource is optional)\n#PASSWORD=juliet\nSUBSCRIBER_RESOURCE=subscriber\nTRACKER_RESOURCE=tracker\n#MQ_ID=8888\n#DB_HOST=localhost\n#DB_PORT=5432\n#DB_NAME=<DATABASE NAME>\n#DB_USER=<DB_USER_NAME>\n#DB_PASSWORD=<DB_PASSWORD>\n')
					logger.error('All the required parameters are not present in the conf file')
					logger.error('#Uncomment fields before use and type in correct credentials.\n#JID=romeo@montague.net/resource (/resource is optional)\n#PASSWORD=juliet\nSUBSCRIBER_RESOURCE=subscriber\nTRACKER_RESOURCE=tracker\n#MQ_ID=8888\n#DB_HOST=localhost\n#DB_PORT=5432\n#DB_NAME=<DATABASE NAME>\n#DB_USER=<DB_USER_NAME>\n#DB_PASSWORD=<DB_PASSWORD>\n')
					sys.exit(0)
			logger.info('Read the required parameters from the conf file')
		else:
			logger.info('conf file is NOT accessible')
			logger.error('Conf file ' + CONF_FILENAME + ' doesn\'t exist')
			sys.exit(1)


	def init_mq(self):
		logger.warn('ImaPresenceSubscriber:Initializing the system V message queue')
		self.mq = sysv_ipc.MessageQueue(int(self.params['mq_id']))
		if self.mq:
			logger.info('Connected to the message queue with key ' +  self.params['mq_id'])
		else:
			logger.error('Failed to connect to message queue')
			sys.exit(1)

	def run(self):
		logger.info('ImaPresenceSubscriber.run called')
		self.read_conf_file()
		self.init_mq()
		logger.info('Message queue initialization done')
		while True:
			logger.info('Will try to fetch message from the message queue')
			msg, _ = self.mq.receive()
			if msg:
				xmppId=msg.decode()
				logger.info('XMPP Id received from message queue is: ' + xmppId)
				xmppId=xmppId.strip()
				logger.info('XMPP Id after stripping is is: ' + xmppId)
				#connect to XMPP server and send the friend(i.e. presence subscription) request
				if self.xmpp_connect():
					roster=self.client.getRoster()
					roster.Subscribe(xmppId)
					logger.info('subscription request sent for '+ xmppId)
					time.sleep(1)
					self.client.disconnect()
				else:
					self.mq.send(msg)
					time.sleep(10)
				self.client=None
				self.con=None
				self.auth=None
			else:
				logger.info('No message was found in the message queue; will sleep now')
				time.sleep(10)

	def xmpp_connect(self):
		logger.warn('ImaPresenceSubscriber.xmpp_connect called')
		#self.read_conf_file()
		logger.info('Read the configurations from the conf file');
		logger.info('Jid as read from the conf file is: ' + self.params['jid'])
		jid=xmpp.protocol.JID(self.params['jid'])
		logger.info('Extracted the jid')
		self.client=xmpp.Client(jid.getDomain(),debug=[])
		logger.info('Called xmpp.Client')
		self.con=self.client.connect(None, None, 0)
		logger.info('called connect')

		if not self.con:
			logger.error('Failed to create connection with the server ' + jid.getDomain())
			return False
		
		logger.info('connection with the server ' + jid.getDomain() + ' established')

		#self.auth=self.client.auth('kamal@iamalive.in', 'namita77')
		self.auth=self.client.auth(jid.getNode(), self.params['password'])
		if not self.auth:
			logger.error('Authentication with the server ' + jid.getDomain() + ' failed')
			return False

		logger.info('Authentication with the server ' + jid.getDomain() + ' successful')
		return True

if __name__ == "__main__":
	logger.info('main invoked')
	daemon = ImaPresenceSubscriber()
	if len(sys.argv) == 2:
		if 'start' == sys.argv[1]:
			logger.warn('Starting the ImaPresenceSubscriber daemon process.')
			daemon.start()
		elif 'stop' == sys.argv[1]:
			logger.warn('Stopping the ImaPresenceSubscriber daemon process')
			daemon.stop()
		elif 'restart' == sys.argv[1]:
			logger.warn('Restarting ImaPresenceSubscriber daemon process')
			daemon.restart()
		else:
			logger.warn('Unknown command; will exit')
			print "Unknown command"
			sys.exit(2)
		sys.exit(0)
	else:
		print "usage: %s start|stop|restart" % sys.argv[0]
		sys.exit(2)

